import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/Login.vue'
import Admin from '@/views/Admin.vue'
import Dashboard from '@/views/admin/Dashboard.vue'
import Managers from '@/views/admin/Managers.vue'
import Clients from '@/views/admin/Clients.vue'
import Services from '@/views/admin/Services.vue'
import Import from '@/views/admin/Import.vue'
import ManagerDetails from '@/views/admin/ManagerDetails.vue'
import ServiceDetails from '@/views/admin/ServiceDetails.vue'
import ManagerDetailView from '@/views/admin/ManagerDetailView.vue'
import ServiceDetailView from '@/views/admin/ServiceDetailView.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '登录'
    }
  },
  {
    path: '/',
    component: Admin,
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: '',
        redirect: '/dashboard'
      },
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: {
          title: '仪表盘'
        }
      },
      {
        path: 'managers',
        name: 'Managers',
        component: Managers,
        meta: {
          title: '客户经理管理'
        }
      },
      {
        path: 'clients',
        name: 'Clients',
        component: Clients,
        meta: {
          title: '客户管理'
        }
      },
      {
        path: 'services',
        name: 'Services',
        component: Services,
        meta: {
          title: '服务项目管理'
        }
      },
      {
        path: 'import',
        name: 'Import',
        component: Import,
        meta: {
          title: '数据导入'
        }
      },
      {
        path: 'manager-details',
        name: 'ManagerDetails',
        component: ManagerDetails,
        meta: {
          title: '客户经理完成情况'
        }
      },
      {
        path: 'manager-details/:id',
        name: 'ManagerDetailView',
        component: ManagerDetailView,
        meta: {
          title: '客户经理详情'
        }
      },
      {
        path: 'service-details',
        name: 'ServiceDetails',
        component: ServiceDetails,
        meta: {
          title: '服务项目进度详情'
        }
      },
      {
        path: 'service-details/:id',
        name: 'ServiceDetailView',
        component: ServiceDetailView,
        meta: {
          title: '服务项目详情'
        }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory('/admin/'),
  routes
})

// 检查是否已登录
const isAuthenticated = () => {
  return localStorage.getItem('isLoggedIn') === 'true'
}

// 路由守卫
router.beforeEach((to, _from, next) => {
  // 设置页面标题
  if (to.meta?.title) {
    document.title = `${to.meta.title} - 客户经理拜访系统`
  }

  // 检查是否需要认证
  if (to.meta?.requiresAuth) {
    if (!isAuthenticated()) {
      next('/login')
      return
    }
  }

  // 如果已登录且访问登录页，重定向到仪表盘
  if (to.path === '/login' && isAuthenticated()) {
    next('/dashboard')
    return
  }

  next()
})

export default router
